<template>
  <div class="teacher-management">
    <div class="header">
      <h2>教师管理</h2>
      <div class="actions">
        <button class="btn btn-primary" @click="showCreateModal = true">
          <i class="fas fa-plus"></i>
          添加教师
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filters">
      <div class="search-box">
        <i class="fas fa-search"></i>
        <input 
          v-model="searchQuery" 
          type="text" 
          placeholder="搜索教师姓名、工号或邮箱"
          @input="handleSearch"
        >
      </div>
      <select v-model="statusFilter" @change="loadTeachers">
        <option value="">全部状态</option>
        <option value="active">启用</option>
        <option value="inactive">禁用</option>
      </select>
    </div>

    <!-- 教师列表 -->
    <div class="table-container">
      <table class="teachers-table">
        <thead>
          <tr>
            <th>
              <input 
                type="checkbox" 
                :checked="isAllSelected" 
                @change="toggleSelectAll"
              >
            </th>
            <th>工号</th>
            <th>姓名</th>
            <th>邮箱</th>
            <th>电话</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="teacher in teachers" :key="teacher.id">
            <td>
              <input 
                type="checkbox" 
                :value="teacher.id" 
                v-model="selectedTeachers"
              >
            </td>
            <td>{{ teacher.employee_id }}</td>
            <td>{{ teacher.name }}</td>
            <td>{{ teacher.email }}</td>
            <td>{{ teacher.phone || '-' }}</td>
            <td>
              <span :class="['status', teacher.status]">
                {{ teacher.status === 'active' ? '启用' : '禁用' }}
              </span>
            </td>
            <td>{{ formatDate(teacher.created_at) }}</td>
            <td>
              <div class="actions">
                <button 
                  class="btn btn-sm btn-outline" 
                  @click="editTeacher(teacher)"
                >
                  编辑
                </button>
                <button 
                  class="btn btn-sm btn-outline" 
                  @click="managePermissions(teacher)"
                >
                  权限
                </button>
                <button 
                  class="btn btn-sm btn-outline" 
                  @click="resetPassword(teacher)"
                >
                  重置密码
                </button>
                <button 
                  :class="['btn', 'btn-sm', teacher.status === 'active' ? 'btn-warning' : 'btn-success']"
                  @click="toggleStatus(teacher)"
                >
                  {{ teacher.status === 'active' ? '禁用' : '启用' }}
                </button>
                <button 
                  class="btn btn-sm btn-danger" 
                  @click="deleteTeacher(teacher)"
                >
                  删除
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button 
        :disabled="currentPage === 1" 
        @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
      <button 
        :disabled="currentPage === totalPages" 
        @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
    </div>

    <!-- 批量操作 -->
    <div v-if="selectedTeachers.length > 0" class="batch-actions">
      <span>已选择 {{ selectedTeachers.length }} 个教师</span>
      <button class="btn btn-danger" @click="batchDelete">
        批量删除
      </button>
    </div>

    <!-- 创建/编辑教师模态框 -->
    <div v-if="showCreateModal || showEditModal" class="modal-overlay" @click="closeModals">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ showCreateModal ? '添加教师' : '编辑教师' }}</h3>
          <button class="close-btn" @click="closeModals">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveTeacher">
            <div class="form-group">
              <label>工号 *</label>
              <input 
                v-model="teacherForm.employee_id" 
                type="text" 
                required
                :disabled="showEditModal"
              >
            </div>
            <div class="form-group">
              <label>姓名 *</label>
              <input v-model="teacherForm.name" type="text" required>
            </div>
            <div class="form-group">
              <label>邮箱 *</label>
              <input v-model="teacherForm.email" type="email" required>
            </div>
            <div class="form-group">
              <label>电话</label>
              <input v-model="teacherForm.phone" type="tel">
            </div>
            <div v-if="showCreateModal" class="form-group">
              <label>密码 *</label>
              <input v-model="teacherForm.password" type="password" required>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-outline" @click="closeModals">
                取消
              </button>
              <button type="submit" class="btn btn-primary">
                {{ showCreateModal ? '创建' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 权限管理模态框 -->
    <div v-if="showPermissionModal" class="modal-overlay" @click="closeModals">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>权限管理 - {{ currentTeacher?.name }}</h3>
          <button class="close-btn" @click="closeModals">&times;</button>
        </div>
        <div class="modal-body">
          <div class="permissions-list">
            <div v-for="permission in availablePermissions" :key="permission.key" class="permission-item">
              <label>
                <input 
                  type="checkbox" 
                  :value="permission.key" 
                  v-model="teacherPermissions"
                >
                {{ permission.name }}
              </label>
              <p class="permission-desc">{{ permission.description }}</p>
            </div>
          </div>
          <div class="form-actions">
            <button type="button" class="btn btn-outline" @click="closeModals">
              取消
            </button>
            <button type="button" class="btn btn-primary" @click="savePermissions">
              保存权限
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { 
  getTeachers, 
  createTeacher, 
  updateTeacher, 
  deleteTeacher,
  batchDeleteTeachers,
  resetTeacherPassword,
  toggleTeacherStatus,
  getTeacherPermissions,
  updateTeacherPermissions
} from '@/api/rbac'

export default {
  name: 'TeacherManagement',
  setup() {
    const teachers = ref([])
    const loading = ref(false)
    const searchQuery = ref('')
    const statusFilter = ref('')
    const selectedTeachers = ref([])
    const currentPage = ref(1)
    const totalPages = ref(1)
    const pageSize = 10

    // 模态框状态
    const showCreateModal = ref(false)
    const showEditModal = ref(false)
    const showPermissionModal = ref(false)
    const currentTeacher = ref(null)

    // 表单数据
    const teacherForm = reactive({
      employee_id: '',
      name: '',
      email: '',
      phone: '',
      password: ''
    })

    // 权限相关
    const teacherPermissions = ref([])
    const availablePermissions = ref([
      { key: 'create_exam', name: '创建考试', description: '允许创建新的考试' },
      { key: 'edit_exam', name: '编辑考试', description: '允许编辑已有考试' },
      { key: 'delete_exam', name: '删除考试', description: '允许删除考试' },
      { key: 'create_question', name: '创建题目', description: '允许创建新题目' },
      { key: 'edit_question', name: '编辑题目', description: '允许编辑题目' },
      { key: 'delete_question', name: '删除题目', description: '允许删除题目' },
      { key: 'view_results', name: '查看成绩', description: '允许查看考试成绩' },
      { key: 'export_results', name: '导出成绩', description: '允许导出考试成绩' }
    ])

    // 计算属性
    const isAllSelected = computed(() => {
      return teachers.value.length > 0 && selectedTeachers.value.length === teachers.value.length
    })

    // 方法
    const loadTeachers = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          pageSize: pageSize,
          search: searchQuery.value,
          status: statusFilter.value
        }
        const response = await getTeachers(params)
        teachers.value = response.data.data
        totalPages.value = Math.ceil(response.data.total / pageSize)
      } catch (error) {
        console.error('加载教师列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
      loadTeachers()
    }

    const changePage = (page) => {
      currentPage.value = page
      loadTeachers()
    }

    const toggleSelectAll = () => {
      if (isAllSelected.value) {
        selectedTeachers.value = []
      } else {
        selectedTeachers.value = teachers.value.map(t => t.id)
      }
    }

    const editTeacher = (teacher) => {
      currentTeacher.value = teacher
      Object.assign(teacherForm, {
        employee_id: teacher.employee_id,
        name: teacher.name,
        email: teacher.email,
        phone: teacher.phone
      })
      showEditModal.value = true
    }

    const saveTeacher = async () => {
      try {
        if (showCreateModal.value) {
          await createTeacher(teacherForm)
        } else {
          await updateTeacher(currentTeacher.value.id, teacherForm)
        }
        closeModals()
        loadTeachers()
      } catch (error) {
        console.error('保存教师失败:', error)
      }
    }

    const deleteTeacher = async (teacher) => {
      if (confirm(`确定要删除教师 ${teacher.name} 吗？`)) {
        try {
          await deleteTeacher(teacher.id)
          loadTeachers()
        } catch (error) {
          console.error('删除教师失败:', error)
        }
      }
    }

    const batchDelete = async () => {
      if (confirm(`确定要删除选中的 ${selectedTeachers.value.length} 个教师吗？`)) {
        try {
          await batchDeleteTeachers(selectedTeachers.value)
          selectedTeachers.value = []
          loadTeachers()
        } catch (error) {
          console.error('批量删除失败:', error)
        }
      }
    }

    const resetPassword = async (teacher) => {
      if (confirm(`确定要重置 ${teacher.name} 的密码吗？`)) {
        try {
          await resetTeacherPassword(teacher.id)
          alert('密码重置成功')
        } catch (error) {
          console.error('重置密码失败:', error)
        }
      }
    }

    const toggleStatus = async (teacher) => {
      const newStatus = teacher.status === 'active' ? 'inactive' : 'active'
      try {
        await toggleTeacherStatus(teacher.id, newStatus)
        loadTeachers()
      } catch (error) {
        console.error('切换状态失败:', error)
      }
    }

    const managePermissions = async (teacher) => {
      currentTeacher.value = teacher
      try {
        const response = await getTeacherPermissions(teacher.id)
        teacherPermissions.value = response.data.permissions || []
        showPermissionModal.value = true
      } catch (error) {
        console.error('获取权限失败:', error)
      }
    }

    const savePermissions = async () => {
      try {
        await updateTeacherPermissions(currentTeacher.value.id, teacherPermissions.value)
        closeModals()
        alert('权限更新成功')
      } catch (error) {
        console.error('保存权限失败:', error)
      }
    }

    const closeModals = () => {
      showCreateModal.value = false
      showEditModal.value = false
      showPermissionModal.value = false
      currentTeacher.value = null
      Object.assign(teacherForm, {
        employee_id: '',
        name: '',
        email: '',
        phone: '',
        password: ''
      })
    }

    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN')
    }

    onMounted(() => {
      loadTeachers()
    })

    return {
      teachers,
      loading,
      searchQuery,
      statusFilter,
      selectedTeachers,
      currentPage,
      totalPages,
      showCreateModal,
      showEditModal,
      showPermissionModal,
      currentTeacher,
      teacherForm,
      teacherPermissions,
      availablePermissions,
      isAllSelected,
      loadTeachers,
      handleSearch,
      changePage,
      toggleSelectAll,
      editTeacher,
      saveTeacher,
      deleteTeacher,
      batchDelete,
      resetPassword,
      toggleStatus,
      managePermissions,
      savePermissions,
      closeModals,
      formatDate
    }
  }
}
</script>

<style scoped>
.teacher-management {
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h2 {
  margin: 0;
  color: #1f2937;
}

.filters {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;
}

.search-box {
  position: relative;
  flex: 1;
  max-width: 400px;
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #6b7280;
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.filters select {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.table-container {
  overflow-x: auto;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.teachers-table {
  width: 100%;
  border-collapse: collapse;
}

.teachers-table th,
.teachers-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.teachers-table th {
  background: #f9fafb;
  font-weight: 600;
  color: #374151;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status.active {
  background: #d1fae5;
  color: #065f46;
}

.status.inactive {
  background: #fee2e2;
  color: #991b1b;
}

.actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-outline {
  background: transparent;
  color: #6b7280;
  border: 1px solid #d1d5db;
}

.btn-success {
  background: #10b981;
  color: white;
}

.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn:hover {
  opacity: 0.8;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 24px;
}

.batch-actions {
  position: fixed;
  bottom: 24px;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  gap: 16px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
  color: #1f2937;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6b7280;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 4px;
  font-weight: 500;
  color: #374151;
}

.form-group input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.permissions-list {
  max-height: 400px;
  overflow-y: auto;
}

.permission-item {
  padding: 12px 0;
  border-bottom: 1px solid #e5e7eb;
}

.permission-item:last-child {
  border-bottom: none;
}

.permission-item label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  cursor: pointer;
}

.permission-desc {
  margin: 4px 0 0 24px;
  font-size: 12px;
  color: #6b7280;
}
</style>